package com.crud.web; /**
 * @author wzm
 * @create 2023-05-08 14:45
 */

import com.crud.bean.Employee;
import com.crud.service.EmployeeService;
import com.crud.service.impl.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addEmp")
public class AddServlet extends HttpServlet {
    private EmployeeService service = new EmployeeServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //接收请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //String=Int
        int age = Integer.parseInt(request.getParameter("age"));
        String phone = request.getParameter("phone");
        int status = Integer.parseInt(request.getParameter("status"));

        //封装成实体对象
        Employee employee = new Employee(username,password,age,phone,status);

        //调用Service
        boolean add = service.add(employee);
//        boolean add =false;
        if (add){
            //增加成功 查询全部数据重新展示
            //转发 地址不变会导致多次新增
            //request.getRequestDispatcher("/findAll").forward(request,response);

            //重定向
            response.sendRedirect(request.getContextPath()+"/findAll");
        }else{
//            失败的操作
            request.setAttribute("msg","新增数据失败");
            request.getRequestDispatcher("employee_add.jsp").forward(request,response);
        }


    }
}
